import axios from 'axios'
import router from '../router/index'
import { MessagePlugin } from 'tdesign-vue-next'
import { useAuthStore } from '../stores/AuthToken'

function request(config) {
  const authStore = useAuthStore()
  // 创建axios实例
  const instance = axios.create({
    baseURL: '/api',
    // 生产环境 https://f812731b17.yicp.fun/DS
    timeout: 5000
  })

  // 请求拦截器配置
  instance.interceptors.request.use(
    (config) => {
      if (authStore.verifyAuth()) {
        config.headers.Authorization = authStore.auth.token
      }
      return config
    },
    (error) => {
      return Promise.error(error)
    }
  )

  // 响应拦截器
  instance.interceptors.response.use(
    (res) => {
      if (res.data.code === 200 || res.data.status) return res.data.data
      if (!res.data.status) {
        switch (res.data.code) {
          case 2011:
          case 2012:
          case 2015:
          case 2001:
            // token问题-->清除store 本地token
            MessagePlugin.error({
              content:
                (res.data.message || '权限不足，无法访问服务器') + '，即将为您跳转到登陆界面...',
              placement: 'top',
              onDurationEnd: () => router.push('/login/byPassword')
            })
            break

          default:
            MessagePlugin.error(res.data.message || '服务器错误')
            break
        }
      }
      return Promise.reject(res.data)
    },
    (err) => {
      MessagePlugin.error('服务器错误，获取请求失败')
      return Promise.reject(err)
    }
  )

  return instance(config)
}

export default request
